var util = require('../../utils/util.js');
var app =getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    search_txt: "",
    detail: [],
    hot_list: [],
    local_search_list: [],
    is_home: true,
    cart_count: 0,
    sum: 0,
    store_id: "",
    cur_page: 1,
    page_num: 10,
    has_null: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    if (options.name) {
      var e = {
        detail: {
          value: options.name,
        }
      }
      that.inputHandle(e);
    }
    if (options.store_id) {
      that.setData({
        store_id: options.store_id,
      })
    } else {
      that.setData({
        store_id: "",
      })
    }

    var local_search_list = wx.getStorageSync('local_search_list');
    if (local_search_list == '') {
      local_search_list = [];
    }
    that.setData({
      local_search_list: local_search_list,
    })
    util.postUrl('search/hot_words', {}, function(res) {
      that.setData({
        hot_list: res.data.datas,
      })
    })
    that.initRed();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  inputHandle: function(e) {
    var t = e.detail.value;
    var that = this;
    if (t == '') {
      return;
    }
    this.setData({
      search_txt: t,
      is_home: false,
      detail: [],
      cur_page: 1,

    })
    that.getList();



  },
  getList: function() {
    var that = this;
    that.setData({
      has_null: false,
    })
    var t = that.data.search_txt;
    var local_search_list = wx.getStorageSync('local_search_list');
    if (local_search_list == '') {
      local_search_list = [];
    }
    if (local_search_list.indexOf(t) == -1) {
      local_search_list.unshift(t);
    }
    if (local_search_list.length > 10) {
      local_search_list.pop();
    }
    wx.setStorageSync('local_search_list', local_search_list)
    util.postUrl("search/index", {
      cur_page: that.data.cur_page,
      page_num: that.data.page_num,
      key_words: t,
      store_id: that.data.store_id,
      user_city_id: app.user_city_id,
    }, function(res) {
      console.log(res.data.datas);
      var temp = res.data.datas.goods_list;
      if (that.data.cur_page == 1) {
        that.setData({
          detail: [],
        })
      }
      if (temp.length > 0) {
        that.setData({
          cur_page: parseInt(that.data.cur_page) + 1,
        })
      }
      for (var i = 0; i < temp.length; i++) {
        if (temp[i].min_goods_price == temp[i].max_goods_price) {
          temp[i].price = temp[i].min_goods_price
        } else {
          temp[i].price = temp[i].min_goods_price + " - ￥" + temp[i].max_goods_price
        }
        if (temp[i].spec_list) {
          for (var j = 0; j < temp[i].spec_list.length; j++) {
            var temp_goods = wx.getStorageSync('temp_goods');
            temp[i].spec_list[j].num = 0;
            if (wx.getStorageSync('token') == '') {
              for (var z = 0; z < temp_goods.length; z++) {
                if (temp_goods[z].goods_id == temp[i].spec_list[j].goods_id) {
                  temp[i].spec_list[j].num = temp_goods[z].quantity;
                }
              }
            } else {
              var member_carts = res.data.datas.member_carts;
              var num = member_carts[temp[i].spec_list[j].goods_id];
              if (num) {
                temp[i].spec_list[j].num = num;
              }
            }
          }
        }
      }
      var detail = that.data.detail;
      detail = detail.concat(temp);
      if (detail.length == 0) {
        that.setData({
          has_null: true,
        })
      } else {
        that.setData({
          has_null: false,
        })
      }
      that.setData({
        detail: detail,
      })
    })

  },
  handlescrolltolower: function() {
    this.getList();
  },
  //点击减号
  bindMinus: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];

    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (item.num - 1 < 0) {
      return;
    }
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          if (item.num - 1 == 0) {
            temp_goods.splice(i, 1);
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
          } else {
            temp_goods[i].quantity = item.num - 1;
            temp_goods[i].goods_num = item.num - 1;
          }
        }
      }
      item.num = item.num - 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);
      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      if (item.num - 1 == 0) {
        util.postUrl("cart/cart_remove", {
          cart_id: item.goods_id,
          del_type: 2,
        }, function(res) {
          if (res) {
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
            wx.setStorageSync("check_list", check_list);
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          }
        })
      } else {
        util.postUrl('cart/cart_add', {
          goods_id: item.goods_id,
          quantity: item.num - 1,
        }, function(res) {
          if (res) {
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          } else {}
        })
      }
    }
  },

  /* 点击加号 */
  bindPlus: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];
    item.num = parseInt(item.num);
    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num + 1;
          temp_goods[i].goods_num = item.num + 1;
          flag = false;
        }
      }
      if (flag) {
        check_list.push(item.goods_id);
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num + 1,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num + 1,
          goods_price: item.goods_price,
        });
      }
      item.num = item.num + 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);

      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: item.num + 1,
      }, function(res) {
        if (res) {
          if (res.data.code == 400) {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 2000
            })
            return;
          }
          if (check_list.indexOf(item.goods_id) == -1) {
            check_list.push(item.goods_id);
          }
          wx.setStorageSync('check_list', check_list);
          console.log(check_list);
          item.num = item.num + 1;
          that.setData({
            detail: temp
          });
          that.initRed();
        } else {}
      })
    }

  },
  /* 输入框事件 */
  bindManual: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;

    var item = temp[index].spec_list[spec_index];
    // var index = e.currentTarget.dataset.index;
    console.log(item);
    var temp_num = parseInt(item.num);
    // 将数值与状态写回
    console.log(e.detail.value)
    if (e.detail.value == '' || e.detail.value == 0) {
      e.detail.value = 1;
    }
    item.num = parseInt(e.detail.value);
    that.setData({
      detail: temp,
    })
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num;
          temp_goods[i].goods_num = item.num;
          flag = false;
        }
      }
      if (flag) {
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num,
          goods_price: item.goods_price,
        });
      }
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      console.log('temp_goods', wx.getStorageSync('temp_goods'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: parseInt(e.detail.value),
      }, function(res) {
        if (res.data.code == 200) {
          that.initRed();

        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
          item.num = temp_num;
          that.setData({
            detail: temp
          });
          that.initRed();
        }
      })
    }

  },
  //点击显示隐藏
  onChangeShowState: function(e) {
    var that = this;
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var temp = that.data.detail;
    if (temp[index].showView) {
      temp[index].showView = false;
    } else {
      temp[index].showView = true;
    }
    that.setData({
      detail: temp,
    })
  },
  //更新购物车气泡数
  initRed: function() {
    var that = this;
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      console.log("temp_goods", temp_goods)
      var cart_count = 0;
      var sum = 0;
      if (temp_goods != '') {
        for (let item of temp_goods) {
          cart_count = cart_count + item.quantity;
          sum = sum + parseInt(item.goods_num) * parseFloat(item.goods_price);
        }
      }
      that.setData({
        cart_count: cart_count,
        sum: sum,
      })
      wx.setTabBarBadge({
        index: 2,
        text: cart_count + "",
      })
      if (cart_count == 0) {
        wx.hideTabBarRedDot({
          index: 2,
        })
      }

    } else {
      util.postUrl('cart/cart_count', {}, function(res) {
        if (res.data.code == 200) {
          that.setData({
            cart_count: res.data.datas.count.goods_total_num,
            sum: res.data.datas.count.goods_total_price,
          })
          wx.setTabBarBadge({
            index: 2,
            text: (res.data.datas.count.goods_total_num + ""),
          })
          if (res.data.datas.count.goods_total_num == 0) {

            wx.hideTabBarRedDot({
              index: 2,
            })
          }
        }
      })
    }

  },
  goGoodsDetail: function(e) {
    var item = e.currentTarget.dataset.item;
    item.goods_num = item.num;
    wx.navigateTo({
      url: '../goods-details/goods-details?item=' + JSON.stringify(item),
    })
  },
  handleinput: function(e) {
    var t = e.detail.value;
    var that = this;
    if (t == '') {
      var local_search_list = wx.getStorageSync('local_search_list');
      if (local_search_list == '') {
        local_search_list = [];
      }
      this.setData({
        is_home: true,
        local_search_list: local_search_list,
      })
    }

  },
  click_search: function(e) {
    var that = this;
    var t = e.currentTarget.dataset.t;
    var e = {
      detail: {
        value: t,
      }
    }
    that.setData({
      search_txt: t,
    })
    this.inputHandle(e);
  },
  goCar: function() {
    wx.switchTab({
      url: '../shoppingCar/shoppingCar',
    })
  },
  //清除
  clean_t: function() {
    var that = this;
    wx.setStorageSync('local_search_list', "")
    that.setData({
      local_search_list: [],
    })
  }
})